package com.matrix.common.security.filter;

import com.matrix.common.constant.HeaderConstants;
import com.matrix.common.context.UserContext;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

/**
 * @author 有点甜
 * @since 2025/8/5
 */
@Activate(group = CommonConstants.PROVIDER)
public class ProviderAuthFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            String userId = RpcContext.getServerAttachment().getAttachment(HeaderConstants.USER_ID);
            String userRole = RpcContext.getServerAttachment().getAttachment(HeaderConstants.USER_ROLE);

            if (StringUtils.hasText(userId)) {
                UserContext.setUserId(Long.valueOf(userId));
                UserContext.setUserRole(userRole);
            }

            String traceId = RpcContext.getServerAttachment().getAttachment(HeaderConstants.TRACE_ID);
            if (traceId != null) {
                MDC.put("traceId", traceId);
            }

            return invoker.invoke(invocation);
        } finally {
            UserContext.clear();
            MDC.clear();
        }
    }
}
